home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2495 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.5 KB

  1. Path: access1.digex.net!not-for-mail
  2. From: ell@access1.digex.net (Ell)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Overload of operator=
  5. Date: 18 Jan 1996 02:37:53 GMT
  6. Organization: The Universe
  7. Message-ID: <4dkbq1$mni@news4.digex.net>
  8. References: <30FBCAA1.34A7@novell.com>
  9. NNTP-Posting-Host: access1.digex.net
  10. X-Newsreader: TIN [UNIX 1.3 950824BETA PL0]
  11.  
  12. Greg Johnson (gregjo@novell.com) wrote:
  13. : I want to overload the assignment operator, for some debugging purposes.
  14. : But after I overload the operator, somehow, I need to perform the 
  15. : default assignment. How do I do that if I don't know the exact size
  16. : of the source or destination?
  17. : How do I avoid recursion and perform the default behavior?
  18. : For example:
  19. : class BaseObj {
  20. : public:
  21. :     long x;       
  22. :     BaseObj& operator=(BaseObj&);
  23. :     BaseObj(void) : x(0) {};
  24. : };
  25. : BaseObj& BaseObj::operator=(BaseObj  & ptr)
  26. : {
  27. :     *this = ptr; // this will recursively call operator=
  28.  
  29. This above line only takes effect if the left hand side is a BaseObj. 
  30. Generally, the assignment operator only needs to be defined when a class
  31. has heap based data members.  Generally you do not want to simply assign 
  32. the right hand side (rhs) to the left hand side (lhs) when you need to 
  33. have an assignment operator.  Try the following:
  34.  
  35. BaseObj& operator=(BaseObj& ref)
  36. {
  37.    if (this != &ref)
  38.    { 
  39.       x = ref.long;    // does not call the above overload of '='
  40.    }                    // because the left hand side (lhs) is a 'long'
  41.                         // not a BaseObj class.  so no recursion.
  42.    return *this;
  43. }
  44.  
  45. Elliott
  46.